﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SurveySystem.Core;
using System.ComponentModel;
using System.Diagnostics;
using System.Web.Security;

namespace SurveySystem.Web
{
    public partial class DetailedGroupView : System.Web.UI.Page
    {
        public GroupMemberRole CurrentRole { get; private set; }
        public int GroupId { get; private set; }

        private Group _group;

        public bool IsAdmin
        {
            get { return CurrentRole == GroupMemberRole.Admin || IsOwner; }
        }

        public bool IsOwner
        {
            get { return CurrentRole == GroupMemberRole.Owner; }
        }

        public bool CanDelete(object memberAsObj)
        {
            Member m = memberAsObj as Member;
            return IsAdmin && m.role == GroupMemberRole.Member;
        }

        public bool CanGrantAdminship(object memberAsObj)
        {
            Member m = memberAsObj as Member;
            return IsOwner && m.role == GroupMemberRole.Member;
        }

        public bool CanTakeAdminship(object memberAsObj)
        {
            Member m = memberAsObj as Member;
            return IsOwner && m.role == GroupMemberRole.Admin;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string gidStr = Request.QueryString["groupId"];
            if (!User.Identity.IsAuthenticated || gidStr == null)
                RedirectDefault();
            GroupId = Convert.ToInt32(gidStr);
            _group = GroupsBLL.GetGroup(GroupId);
            

            CurrentRole = GroupsBLL.GetRole(User.Identity.Name, GroupId);

            if (CurrentRole == GroupMemberRole.NotMember)
                exitGroupMultiView.Visible = false;

            lblHead.Text = string.Format("{0} ({1})", _group.name, WebUtils.GetRoleString(CurrentRole));

            lblInfo.Text = "";

            requestsPanel.Visible = IsAdmin;
            GridView_Members.Columns[3].Visible = IsAdmin;
            GridView_Members.Columns[4].Visible = IsOwner;
        }

        private void RedirectDefault()
        {
            Response.Redirect("~/Default.aspx");
        }

        protected void membersSource_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {

        }

        protected void GridView_Requests_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int rowId = Convert.ToInt32(e.CommandArgument);
            Guid userId = (Guid)GridView_Requests.DataKeys[0].Value;
            bool accept = e.CommandName == "AcceptRequest";
            try
            {
                GroupsBLL.HandleJoiningRequest(GroupId, User.Identity.Name, userId, accept);
                lblInfo.Text = "Csatlakozási kérelem " + (accept ? "elfogadva" : "elutasítva");
            }
            catch
            {
                lblInfo.Text = "Valaki más közben lekezelte a kérelmet!";
            }

            GridView_Members.DataBind();
            GridView_Requests.DataBind();
        }

        protected void GridView_Members_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int rowIdx = Convert.ToInt32(e.CommandArgument);
            Guid userId = (Guid)GridView_Members.DataKeys[rowIdx].Values[0];
            int groupId = (int)GridView_Members.DataKeys[rowIdx].Values[1];

            try
            {
                switch (e.CommandName)
                {
                    case "DeleteUser":
                        GroupsBLL.RemoveUser(groupId, userId);
                        break;
                    case "GrantAdminship":
                        GroupsBLL.GrantAdminship(groupId, User.Identity.Name, userId, true);
                        break;
                    case "TakeAdminship":
                        GroupsBLL.GrantAdminship(groupId, User.Identity.Name, userId, false);
                        break;
                    default:
                        break;
                }
            }
            catch
            {
                lblInfo.Text = "Valaki más is állította a felhasználó státuszát, vagy a felhasználó kilépett!";
            }

            GridView_Members.DataBind();
        }

        protected void btnExitGroup_Click(object sender, EventArgs e)
        {
            if (CurrentRole == GroupMemberRole.Owner)
                exitGroupMultiView.ActiveViewIndex = 1;
            else
                exitGroupMultiView.ActiveViewIndex = 2;
        }

        protected void btnCancelExit1_Click(object sender, EventArgs e)
        {
            exitGroupMultiView.ActiveViewIndex = 0;
        }

        protected void btnCancelExit2_Click(object sender, EventArgs e)
        {
            exitGroupMultiView.ActiveViewIndex = 0;
        }

        protected void btnExit_Click(object sender, EventArgs e)
        {
            GroupsBLL.RemoveUser(GroupId, (Guid)Membership.GetUser(User.Identity.Name).ProviderUserKey);
            Response.Redirect("~/MyGroups.aspx");
        }

        protected void btnSelectNewOwnerAndExit_Click(object sender, EventArgs e)
        {
            if (DropDownList_SelectNewOwner.SelectedIndex > -1)
            {
                GroupsBLL.PromoteNewOwner(GroupId, User.Identity.Name,  new Guid(DropDownList_SelectNewOwner.SelectedValue));
                GroupsBLL.RemoveUser(GroupId, (Guid)Membership.GetUser(User.Identity.Name).ProviderUserKey);
                Response.Redirect("~/MyGroups.aspx");
            }

        }


    }
}
